package com.monkeygroup.mygoplus.ecchat.ui.contact;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.Toast;

import com.afun.zxinglib.ScanView.ZXingScannerViewNew;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.common.DefinedView.MyDialog;
import com.monkeygroup.mygoplus.common.utils.Tools;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.ecchat.common.utils.ToastUtil;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactMemberDTO;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/29.
 */
public class ScanAddFriendActivity extends Activity implements ZXingScannerViewNew.ResultHandler, ZXingScannerViewNew.QrSize, View.OnClickListener {
    ZXingScannerViewNew scanView;
    private String scanContent = "";
    private Dialog permissionDialog = null;
    private int scanStatus = 0;
    private final String TAG = "ScanAddFriendActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestCameraPermission();

    }

    private void initUI() {
        findViewById(R.id.layout_back).setOnClickListener(this);
        findViewById(R.id.scan_code).setOnClickListener(this);
    }

    /**
     * 獲取用戶信息
     **/
    private void getUserDetail(String mobile) {
        String requestUrl = RequestUrl.baseUrl + RequestUrl.getUserDetail;
        HttpModel httpModel = new HttpModel(requestUrl, getUserParams(mobile), new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, String> info = (Map) data;

                    ContactMemberDTO member = new ContactMemberDTO();
                    if (info.get("username") != null && !info.get("username").equals("")) {
                        member.setName(info.get("username"));
                    } else if (info.get("userID") != null && !info.get("userID").equals("")) {
                        member.setName(info.get("userID"));
                    } else {
                        member.setName(info.get("mobile"));
                    }

                    member.setId(info.get("mobile"));
                    member.setHeadUrl(info.get("headIcon"));

                    Intent intent = new Intent(ScanAddFriendActivity.this, AddFriendSearchResult.class);
                    intent.putExtra("result", member);
                    startActivity(intent);
                } else {
                    ToastUtil.showMessage(resultMsg);
                }
            }
        }, true);

        httpModel.startRequest();
    }

    private Map<String, String> getUserParams(String mobile) {
        Map<String, String> params = new HashMap<>();
        params.put("mobile", mobile);

        return params;
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (scanStatus == 1) {
            doScan();
        }
    }

    @Override
    public void handleResult(Result rawResult) {
        scanContent = rawResult.toString();

        if (scanContent.contains("mygoqrcode")) {
            String id = "";
            try {
                JSONObject data = new JSONObject(scanContent);
                id = data.getJSONObject("mygoqrcode").getString("codeContent");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            getUserDetail(id);
//            Intent intent = new Intent(ScanAddFriendActivity.this, AddFriendSearchResult.class);
//            intent.putExtra("mobile", id);
//            startActivity(intent);

        } else if (scanContent.startsWith("https") || scanContent.startsWith("http") || scanContent.startsWith("ftp")) {
            try {
                Uri uri = Uri.parse(scanContent);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(ScanAddFriendActivity.this, scanContent, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (scanStatus == 1) {
            scanView.stopCamera();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void setupFormats() {
        List<BarcodeFormat> formats = new ArrayList<>();
        formats.add(BarcodeFormat.QR_CODE);
        if (scanView != null) {
            scanView.setFormats(formats);
        }
    }

    @Override
    public Rect getDetectRect() {
        View view = findViewById(R.id.scan_window);
        int top = ((View) view.getParent()).getTop() + view.getTop();
        int left = view.getLeft();
        int width = view.getWidth();
        int height = view.getHeight();
        Rect rect = null;
        if (width != 0 && height != 0) {
            rect = new Rect(left, top, left + width, top + height);
            addLineAnim(rect);
        }
        return rect;
    }

    private void addLineAnim(Rect rect) {
        ImageView imageView = (ImageView) findViewById(R.id.scanner_line);
        imageView.setVisibility(View.VISIBLE);
        if (imageView.getAnimation() == null) {
            TranslateAnimation anim = new TranslateAnimation(0, 0, 0, rect.height());
            anim.setDuration(2000);
            anim.setRepeatCount(Animation.INFINITE);
            imageView.startAnimation(anim);
        }
    }

    private void initScanView() {
        scanView = new ZXingScannerViewNew(this);
        scanView.setContentView(R.layout.activity_scantool);
        scanView.setQrSize(this);
        setContentView(scanView);

        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (MyGoApplication.statusHight != 0) {
            findViewById(R.id.layout_title).setPadding(0, MyGoApplication.statusHight, 0, 0);
        } else {
            findViewById(R.id.layout_title).setPadding(0, 40, 0, 0);
        }

        setupFormats();
        initUI();

        scanStatus = 1;
    }

    private void doScan() {
        scanView.setResultHandler(this);
        scanView.startCamera(-1);
        scanView.setFlash(false);
        scanView.setAutoFocus(true);
    }

    private static final int CAMERA_STORAGE_REQUEST = 103;

    // 啟動應用的設置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    private void requestCameraPermission() {
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SharedPreferences sp = Tools.getSharePreferences(ScanAddFriendActivity.this, Tools.PERMISSION_STATUS);
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
                    && !sp.getBoolean(Tools.CAMERA_PERMISSION_STATUS, false)) {
                showAppSettingPermission();
                return;
            }

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_STORAGE_REQUEST);
        } else {
            initScanView();

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_STORAGE_REQUEST) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initScanView();
            } else {
                Toast.makeText(ScanAddFriendActivity.this, getResources().getString(R.string.permission_camera_open), Toast.LENGTH_SHORT).show();
                ScanAddFriendActivity.this.finish();
            }
            SharedPreferences sp = Tools.getSharePreferences(ScanAddFriendActivity.this, Tools.PERMISSION_STATUS);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean(Tools.CAMERA_PERMISSION_STATUS, true);
            editor.commit();
        }
    }

    private void showAppSettingPermission() {
        if (permissionDialog == null) {
            permissionDialog = new MyDialog(ScanAddFriendActivity.this, R.style.MyDialogTheme, getResources().getString(R.string.permission_camera_setting), getResources().getString(R.string.permission_setting_cancel), getResources().getString(R.string.permission_do_setting), new MyDialog.OnCommonDoubleClickListener() {
                @Override
                public void doLeftClick() {
                    permissionDialog.dismiss();
                    ScanAddFriendActivity.this.finish();
                }

                @Override
                public void doRightClick() {
                    permissionDialog.dismiss();
                    startAppSettings();
                    ScanAddFriendActivity.this.finish();
                }
            });

            permissionDialog.show();
        } else {
            permissionDialog.show();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.scan_code:
                intent.setClass(ScanAddFriendActivity.this, MyDRCodeActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }
}